module scene {

    export class PKMatchScene extends eui.Component {

        public static readonly SELECT_LEVEL_COMMAND: string = "game.myHandler.select_level";

        public static readonly SYNC_WIN_SCORE: string = "SyncWinScore";

        public static readonly REPLAY_GAME: string = "ReplayGame";

        public static readonly LEAVE_ROOM: string = "LeaveRoom";

        public static readonly GAME_KIND_ID: number = 4;

        public static readonly OK_CODE: number = 200;

        public rootGroup: eui.Group;

        public btnBackImg: eui.Image;

        public userInfoListDataGroup: eui.DataGroup;

        public scroller: eui.Scroller;

        public btnPlayImg: eui.Image;

        public btnInviteImg: eui.Image;

        public bgImg: eui.Image;

        public txtHouse: egret.TextField;

        public txtTip: egret.TextField;

        private btnPlay: ui.PushButton;

        private btnInvite: ui.PushButton;

        private code: string;

        public bottomGroup: eui.Group;

        private pomelo: PomeloForEgret.Pomelo;

        private isConnected: boolean = false;


        private roomInfo: RoomInfo;

        private roomId: string = "";

        // public static ROUTE_SERVER_HOST: string = "test.pk.2zhuji.cn";

        public static ROUTE_SERVER_HOST: string = "pk.2zhuji.cn";
        public static ROUTE_SERVER_PORT: number = 3014;

        private pkGameScene: scene.PkGameScene;

        private pkFinishScene: scene.PKGameFinishScene;

        private startBtnP: egret.Point = new egret.Point();

        private inviteBtnP: egret.Point = new egret.Point();

        public constructor() {
            super();
            this.addEventListener(eui.UIEvent.COMPLETE, this.onComplete, this);
            this.skinName = "resource/assets/GameRes/game/skins/PKMatchSceneSkin.exml";
        }

        public update(data: any): void {
            this.reset();
            manager.DisplayManager.remove(this.pkFinishScene);
            manager.DisplayManager.remove(this.pkGameScene);
            this.setInfo(data.isJoin, data.roomId);
            this.start();
        }


        private userInfoList: Array<RoleInfo> = new Array<RoleInfo>();
        private playTimes: number = 0;
        private isJoin: boolean = false;
        private isGameStarted: boolean = false;

        private reset(): void {
            this.userInfoList = [];
            this.playTimes = 0;
            this.isJoin = false;
            this.isGameStarted = false;
            this.updateData();
        }

        public onComplete(eve: eui.UIEvent): void {
            this.bgImg.width = manager.DisplayManager.STAGE_WIDTH;
            this.bgImg.height = manager.DisplayManager.STAGE_HEIGHT;

            let dataGroup = this.userInfoListDataGroup;
            dataGroup.itemRenderer = HouseMemberItemRender;
            dataGroup.useVirtualLayout = true;
            dataGroup.scrollEnabled = true;

            let tLayout: eui.TileLayout = new eui.TileLayout();

            tLayout.requestedRowCount = 2;
            tLayout.requestedColumnCount = 1;
            tLayout.verticalGap = 23;
            tLayout.horizontalGap = 23;
            dataGroup.layout = tLayout;

            this.scroller.viewport = dataGroup;
            this.scroller.width = dataGroup.width;

            let btn: ui.PushButton = new ui.PushButton(this.btnBackImg);
            btn.addEventListener(ui.PushButton.CLICK, this.onBacked, this);
            this.rootGroup.addChild(btn);

            this.btnPlay = new ui.PushButton(this.btnPlayImg);
            this.btnPlay.addEventListener(ui.PushButton.CLICK, this.onPlay, this);
            this.bottomGroup.addChild(this.btnPlay);

            this.btnInvite = new ui.PushButton(this.btnInviteImg);
            this.btnInvite.addEventListener(ui.PushButton.CLICK, this.onInviteClicked, this);
            this.bottomGroup.addChild(this.btnInvite);

            this.startBtnP.x = this.btnPlay.x;
            this.startBtnP.y = this.btnPlay.y;

            this.inviteBtnP.x = this.btnInvite.x;
            this.inviteBtnP.y = this.btnInvite.y;

            this.updateData();
        }

        public setInfo(isJoin: boolean, roomId: string): void {
            this.isJoin = isJoin;
            this.roomId = roomId;
            this.btnPlay.visible = true;
            this.btnInvite.visible = true;
            this.btnInvite.x = this.inviteBtnP.x;
            this.btnInvite.y = this.inviteBtnP.y;
            if (this.isJoin) {
                this.btnInvite.visible = false;
                this.btnPlay.visible = false;
                this.btnInvite.x = this.bottomGroup.width - this.btnPlayImg.width >> 1;
            }
        }

        public start(): void {
            let that = this;
            if (this.pomelo != null) {
                this.pomelo.disconnect();
            }

            this.pomelo = new PomeloForEgret.Pomelo();
            this.pomelo.on(PomeloForEgret.Pomelo.EVENT_IO_ERROR, function (event) {
                console.error("error", event);
            });

            this.pomelo.on("joinRoomNotify", function (event) {
                console.error("joinRoomNotify:", event);
                that.addUser(event.userInfo);
            });

            this.pomelo.on("leaveRoomNotify", function (event) {
                console.error("leaveRoomNotify:", event);
                that.removeUser(event.userInfo);
            });

            this.pomelo.on("onGameReady", function (event) {
                console.error("onGameReady:", event);
                that.setReady();
            });

            this.pomelo.on("onGameStart", function (event) {
                console.error("onGameStart:", event);
                that.sendSelectLevelCommand();
            });
            //
            // this.pomelo.on("onGameOver", function (event) {
            //     that.onGameOver(event);
            // });

            this.pomelo.on("game.gameHandler.sendEvent", function (event) {
                console.error("game.gameHandler.sendEvent:", event);
                that.handleCustomMessage(event);
            });

            this.pomelo.on("userInput", function (event) {
                that.handleCustomMessage(event);
            });

            this.pomelo.init({
                host: PKMatchScene.ROUTE_SERVER_HOST,
                port: PKMatchScene.ROUTE_SERVER_PORT,
            }, function () {
                that.pomelo.request('gate.gateHandler.queryEntry', {}, data => {
                    that.pomelo.disconnect();
                    if (data.code !== 200) {
                        throw new Error('请求游戏服务器地址出错');
                    }
                    const {host, port} = data;
                    that.connect(host, port);
                });
            });
        }

        private handleCustomMessage(data: any): void {
            egret.log("处理自定义消息:", data);
            data = data.data;
            if (data.command == PKMatchScene.SELECT_LEVEL_COMMAND) {
                this.level = data.level;
                this.onGameStart();
            } else if (data.command == PKMatchScene.SYNC_WIN_SCORE) {
                let wechatId: string = data.wechatId;
                this.setWiner(wechatId, data.seconds);
                this.showFinishScene();
            } else if (data.command == PKMatchScene.REPLAY_GAME) {
                this.replay();
            } else if (data.command == PKMatchScene.LEAVE_ROOM) {
                this.onRoleLeaveRoom(data.wechatId);
                egret.log("PKMatchScene.LEAVE_ROOM:", PKMatchScene.LEAVE_ROOM);
                if (this.roomInfo.ownerId == data.wechatId) {
                    egret.log("重新创建房间");
                    this.showRoomMasterLeave();
                }
            }
        }

        private showRoomMasterLeave(): void {
            let page: scene.PkMasterLeaveScene = new scene.PkMasterLeaveScene();
            this.addChild(page);
        }

        private onRoleLeaveRoom(wechatId: string): void {
            for (let i: number = 0; i < this.userInfoList.length; i++) {
                let roleInfo: RoleInfo = this.userInfoList[i];
                if (roleInfo.wechatId == wechatId) {
                    roleInfo.isReady = false;
                }
            }
            this.updateData();
        }

        private replay(): void {
            manager.DisplayManager.remove(this.pkGameScene);
            manager.DisplayManager.remove(this.pkFinishScene);
        }

        private showFinishScene(): void {
            if (this.pkFinishScene == null) {
                this.pkFinishScene = new scene.PKGameFinishScene();
            }
            this.hideChildScene();
            this.pkFinishScene.addEventListener(PKGameFinishScene.REPLAY, this.onRelayClicked, this);
            this.addChild(this.pkFinishScene);
            this.pkFinishScene.update(this.userInfoList);
        }

        private hideChildScene(): void {
            manager.DisplayManager.remove(this.pkGameScene);
            manager.DisplayManager.remove(this.pkFinishScene);
        }

        private onRelayClicked(eve: egret.Event): void {
            this.sendReplayCommand();
            this.replay();
        }

        private sendReplayCommand(): void {
            let level: number = manager.RandomManager.getRandRange(6, 10);
            this.level = level;
            this.sendCustomMessage({
                command: PKMatchScene.REPLAY_GAME,
                level: level
            });
        }

        private sendCustomMessage(msgData: any): void {
            const param = {
                msgType: "userInput",
                msgData: msgData
            };
            this.pomelo.request('game.gameHandler.sendEvent', param, (resp) => {
                console.log(resp);
            });
        }


        private onGameOver(data: any): void {
            egret.log("PK结束:", data);
            if (this.pkGameScene != null) {
                this.pkGameScene.stop();
            }
        }

        private updateRoom(): void {
            let len = this.userInfoList.length;
            for (let i: number = 0; i < len; i++) {
                let user = this.userInfoList[i];
                user.isOwner = false;
                if (this.roomInfo.ownerId == user.wechatId) {
                    this.txtHouse.text = user.wechatName + "的房间";
                    user.isOwner = true;
                }
            }
        }

        private onInviteClicked(eve: egret.Event): void {
            if (this.playTimes > 0 && this.getReadyUserCount() < 2) {
                egret.log("重新创建房间");
                this.recreateRoom();
                return;
            }
            this.inviteFriend();
        }

        private inviteFriend(): void {
            let info: manager.ShareInfo = manager.GameManager.getInstance().adManager.getShareInfo();
            manager.GameManager.getInstance().share(info.title, info.img, null, manager.LaunchOptionsManager.ROOM_ID + "=" + this.roomInfo.roomId);
        }

        //重新创建房间
        private recreateRoom(): void {
            egret.log("重新创建房间");
            let that = this;
            this.reset();
            wx.showModal({
                title: '提示',
                content: '房间已失效，可重新创建创建房间',
                confirmText: "创建房间",
                showCancel: false,
                success: res => {
                    if (res.confirm) {
                        that.start();
                    } else if (res.cancel) {
                    }
                },
                complete: function (res) {
                }
            });
        }

        public getReadyUserCount(): number {
            let len = this.userInfoList.length;
            let readyUserCount: number = 0;
            for (let i: number = 0; i < len; i++) {
                if (this.userInfoList[i].isReady) {
                    readyUserCount++;
                }
            }
            return readyUserCount;
        }

        private onPlay(eve: egret.Event): void {
            if (this.isJoin) {
                return;
            }

            if (this.playTimes > 0 && this.getReadyUserCount() < 2) {
                egret.log("重新创建房间");
                this.recreateRoom();
                return;
            }

            let that = this;
            if (this.getReadyUserCount() < 2) {
                wx.showModal({
                    title: '提示',
                    content: '房间未满两人，不能开始',
                    confirmText: "邀请好友",
                    showCancel: false,
                    success: res => {
                        if (res.confirm) {
                            that.inviteFriend();
                        } else if (res.cancel) {
                        }
                    },
                    complete: function (res) {
                    }
                });
                return;
            }
            if (this.isGameStarted) {
                this.sendSelectLevelCommand();
            } else {
                this.sendStartCommand();
                this.isGameStarted = true;
            }
        }

        private sendSelectLevelCommand(): void {
            if (this.isJoin) {
                return;
            }
            // let level: number = manager.RandomManager.getRandRange(50, 500);
            let level: number = manager.RandomManager.getRandRange(6, 10);
            this.level = level;
            this.sendCustomMessage({
                command: PKMatchScene.SELECT_LEVEL_COMMAND,
                level: level
            });
            this.onGameStart();
        }

        private sendStartCommand(): void {
            this.pomelo.request("match.matchHandler.startGame", {}, data => {
                egret.log("");
                if (data.code == PKMatchScene.OK_CODE) {
                }
            });
        }

        private onGameStart(): void {
            if (this.pkGameScene == null) {
                this.pkGameScene = new PkGameScene();
            }
            this.playTimes++;
            let readyRoleInfos: Array<RoleInfo> = [];
            for (let i: number = 0; i < this.userInfoList.length; i++) {
                let roleInfo: RoleInfo = this.userInfoList[i];
                if (roleInfo.isReady) {
                    readyRoleInfos.push(roleInfo);
                }
            }
            this.pkGameScene.setMembers(readyRoleInfos);
            this.addChild(this.pkGameScene);
            this.pkGameScene.setLevel(this.level);
            this.pkGameScene.addEventListener(scene.PkGameScene.PK_FINISH, this.onPkFinish, this);
        }

        private costSeconds: number;

        private onPkFinish(eve: egret.Event): void {
            this.costSeconds = eve.data;
            this.win();
        }

        private win(): void {
            let openId: string = manager.GameManager.getInstance().openid;
            this.sendCustomMessage({
                "seconds": this.costSeconds,
                "command": scene.PKMatchScene.SYNC_WIN_SCORE,
                "wechatId": manager.GameManager.getInstance().openid,
            });
            this.setWiner(openId, this.costSeconds);
            this.showFinishScene();
        }

        public updateData(): void {
            this.userInfoListDataGroup.dataProvider = new eui.ArrayCollection(this.userInfoList);
            this.updateRoom();
        }

        private onBacked(eve: egret.Event): void {
            let that = this;

            if (this.isJoin) {
                wx.showModal({
                    title: '提示',
                    content: '退出对战后,只能通过原来的分享链接进入',
                    confirmText: "退出",
                    success: res => {
                        if (res.confirm) {
                            that.exit();
                        } else if (res.cancel) {
                        }
                    },
                    complete: function (res) {
                    }
                });
            } else {
                wx.showModal({
                    title: '提示',
                    content: '关闭房间，其余玩家也将退出游戏',
                    confirmText: "退出",
                    success: res => {
                        if (res.confirm) {
                            that.exit();
                        } else if (res.cancel) {
                        }
                    },
                    complete: function (res) {
                    }
                });
            }
            this.isJoin = false;
            this.isGameStarted = false;
            this.isConnected = false;
        }

        private exit(): void {
            this.leaveRoom();
            let event: events.SceneEvent = new events.SceneEvent(game.SceneIds.START_SCENE_ID, {});
            facade.GameFacade.getInstance().dispatchEvent(event);
        }

        protected createChildren() {
            super.createChildren();
        }

        private setWiner(wechatId: string, seconds: number): void {
            let len = this.userInfoList.length;
            for (let i: number = 0; i < len; i++) {
                let user = this.userInfoList[i];
                user.isWinner = false;
                user.status = "未完成";
                if (wechatId == user.wechatId) {
                    user.isWinner = true;
                    user.status = "" + seconds + "S";
                }
            }
        }

        private addUser(userInfo: RoleInfo): void {
            this.removeUser(userInfo);
            let isFound: boolean = false;
            let len: number = this.userInfoList.length - 1;
            for (let i: number = len; i >= 0; i--) {
                let roleInfo: RoleInfo = this.userInfoList[i];
                if (userInfo.wechatId == roleInfo.wechatId) {
                    roleInfo.status = "准备";
                    roleInfo.isReady = true;
                    isFound = true;
                }
            }
            if (!isFound) {
                this.userInfoList.push(userInfo);
            }
            userInfo.status = "准备";
            userInfo.isReady = true;
            this.updateData();
        }

        private removeUser(userInfo: RoleInfo, isUpdated: boolean = true): void {
            let len: number = this.userInfoList.length - 1;
            for (let i: number = len; i >= 0; i--) {
                let roleInfo: RoleInfo = this.userInfoList[i];
                if (userInfo.wechatId == roleInfo.wechatId) {
                    roleInfo.status = "离开";
                    roleInfo.isReady = false;
                }
            }
            if (isUpdated) {
                this.updateData();
            }
        }

        private wxCodeLogin(): void {
            let that = this;
            that.pomelo.request("connector.entryHandler.wxlogin", {
                "code": that.code,
                "appToken": manager.GameManager.getInstance().getAppToken()
            }, data => {
                if (data.code == PKMatchScene.OK_CODE) {
                    if (that.isJoin) {
                        that.joinRoom(that.roomId);
                    } else {
                        that.createRoom();
                    }
                }
            });
        }

        private level: number;

        //发起准备好的指令
        private setReady(): void {
            let that = this;
            that.pomelo.request("game.gameHandler.gameSceneReady", {}, data => {
                if (data.code == PKMatchScene.OK_CODE) {
                }
            });
        }

        private connect(host: string, port: number): void {
            let that = this;
            this.pomelo.init({
                host: host,
                port: port,
                reconnect: true
            }, function () {
                that.isConnected = true;
                that.wxLogin();
            });
        }

        private wxLogin(): void {
            let that = this;
            wx.login({
                success: function (res) {
                    if (res.code) {
                        egret.log("获取code1:", res.code);
                        that.code = res.code;
                        // that.wxCodeLogin();
                    } else {
                        console.log('登录失败！' + res.errMsg)
                    }
                },
                fail: function (res) {

                },
                complete: function (res) {

                }
            });
        }

        //加入房间即可准备Ready
        public joinRoom(roomId: string): void {
            egret.log("join room");
            let that = this;
            that.pomelo.request("match.matchHandler.joinRoom", {
                "gameKindId": PKMatchScene.GAME_KIND_ID,
                "roomId": roomId,
            }, data => {
                if (data.code == PKMatchScene.OK_CODE) {
                    that.userInfoList = data.userInfoList;
                    that.setPrepare("准备");
                    that.roomInfo = data.roomInfo;
                    that.updateData();
                    that.isJoin = true;
                    that.setInfo(that.isJoin, that.roomInfo.roomId);
                    this.txtTip.text = "等待房主开始游戏";
                } else {
                    that.showCreateRoomTip();
                }
            });
        }

        private showCreateRoomTip(): void {
            let that = this;
            wx.showModal({
                title: '提示',
                content: '房间已失效，可自己创建房间',
                confirmText: "创建房间",
                showCancel: false,
                success: res => {
                    if (res.confirm) {
                        that.createRoom();
                    } else if (res.cancel) {
                    }
                },
                complete: function (res) {
                }
            });
        }

        //创建房间即可准备Ready
        private createRoom(): void {
            egret.log("create room");
            let that = this;
            that.pomelo.request("match.matchHandler.createRoom", {
                "gameKindId": PKMatchScene.GAME_KIND_ID,
            }, data => {
                if (data.code == PKMatchScene.OK_CODE) {
                    that.reset();
                    that.userInfoList = data.userInfoList;
                    that.setPrepare("准备");
                    that.roomInfo = data.roomInfo;
                    that.isJoin = false;
                    that.updateData();
                    that.setInfo(that.isJoin, that.roomInfo.roomId);
                    that.showFriendModal();
                    this.txtTip.text = "等待邀请好友来PK";
                }
            });
        }

        private setPrepare(status: string = "准备"): void {
            for (let i: number = 0; i < this.userInfoList.length; i++) {
                let roleInfo: RoleInfo = this.userInfoList[i];
                roleInfo.status = status;
                roleInfo.isReady = true;
            }
        }


        private showFriendModal(): void {
            let that = this;
            wx.showModal({
                title: '提示',
                content: '请邀请好友加入',
                confirmText: "邀请好友",
                showCancel: false,
                success: res => {
                    if (res.confirm) {
                        that.inviteFriend();
                    } else if (res.cancel) {
                    }
                },
                complete: function (res) {
                }
            });
        }

        private leaveRoom(): void {
            egret.log("join room");
            this.sendCustomMessage({
                command: PKMatchScene.LEAVE_ROOM,
                wechatId: manager.GameManager.getInstance().openid,
            });
            this.pomelo.request("match.matchHandler.leaveRoom", {}, data => {
                if (data.code == PKMatchScene.OK_CODE) {
                }
            });
            this.pomelo.disconnect();
            this.pomelo = null;
        }
    }


}